#include "snowboy/snowboy-detect-c-wrapper.h"
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include "record.h"
#include "stt.h"
#include "config.h"
#include "chat.h"
#include "IntelPubTrans.h"
#include "tts.h"

static int wake_running = 0;

int is_wake_running()
{
    return wake_running;
}

void stop_wake()
{
    wake_running = 0;
}

void *wake(void *arg)
{
    wake_running = 1;

    // 创建snowboy检测器
    SnowboyDetect *detector = SnowboyDetectConstructor("common.res", "siri.pmdl");
    if (!detector)
    {
        return NULL;
    }
    SnowboyDetectSetSensitivity(detector, "0.5");

    // 获取检测器支持的音频数据参数
    int bits = SnowboyDetectBitsPerSample(detector);
    int channels = SnowboyDetectNumChannels(detector);
    int rate = SnowboyDetectSampleRate(detector);

    printf("采样深度: %d\n", bits);
    printf("声道数量: %d\n", channels);
    printf("采样频率: %d\n", rate);

    // 打开音频采集设备
    snd_pcm_uframes_t period = 999;
    snd_pcm_t *capture = record_open("hw:0,1", SND_PCM_FORMAT_S16_LE, channels, rate, &period);
    if (!capture)
    {
        return NULL;
    }

    char *buffer = malloc(snd_pcm_frames_to_bytes(capture, period));
    if (!buffer)
    {
        perror("malloc");
        record_close(capture);
        SnowboyDetectDestructor(detector);
        return NULL;
    }

    int recording = 0;
    int silence = 0;
    FILE *memstream = NULL;
    char *audio = NULL;
    size_t audio_size = 0;

    // 读取配置文件中的平台密钥
    cJSON *config = read_config("config.json");
    if (!config)
    {
        free(buffer);
        record_close(capture);
        SnowboyDetectDestructor(detector);
        return NULL;
    }

    cJSON *authtoken = cJSON_GetObjectItem(config, "authtoken");
    if (!authtoken)
    {
        fprintf(stderr, "配置文件错误: 找不到 'authtoken' 字段\n");
        cJSON_Delete(config);
        free(buffer);
        record_close(capture);
        SnowboyDetectDestructor(detector);
        return NULL;
    }

    // 创建会话
    char *conv_id = create_conversation(authtoken->valuestring);
    if (!conv_id)
    {
        fprintf(stderr, "创建会话失败\n");
        cJSON_Delete(config);
        free(buffer);
        record_close(capture);
        SnowboyDetectDestructor(detector);
        return NULL;
    }

    while (wake_running)
    {
        snd_pcm_sframes_t frames = snd_pcm_readi(capture, buffer, period);
        if (frames < 0)
        {
            fprintf(stderr, "Error from read: %s\n", snd_strerror(frames));
            snd_pcm_recover(capture, frames, 0);
            continue;
        }

        int status = SnowboyDetectRunDetection(detector, (int16_t *)buffer, snd_pcm_frames_to_bytes(capture, frames) / sizeof(int16_t), 0);
        if (status > 0)
        {
            printf("检测到唤醒词，开始录音\n");
            recording = 1;
            memstream = open_memstream(&audio, &audio_size);
            if (!memstream)
            {
                perror("open_memstream");
                continue;
            }
        }

        if (recording)
        {
            if (status == -2)
            {
                silence++;
            }

            if (status == 0)
            {
                silence = 0;
            }

            if (silence > 32)
            {
                printf("停止录音\n");
                recording = 0;
                silence = 0;
                if (memstream)
                {
                    fclose(memstream);
                    memstream = NULL;
                }

                if (audio_size)
                {
                    snd_pcm_drop(capture);
                    char *text = speech_to_text(audio, audio_size);
                    if (text)
                    {
                        puts(text);

                        // 调用 chat 函数
                        char *answer = chat(authtoken->valuestring, conv_id, text);
                        if (answer)
                        {
                            char *navigation_summary = sum(answer);
                            printf("%s\n", navigation_summary);
                            text_to_speech(navigation_summary);
                            free(answer);
                        }
                        free(text);
                    }
                    snd_pcm_prepare(capture);
                }
                free(audio);
                audio = NULL;
                audio_size = 0;
            }

            if (memstream)
            {
                fwrite(buffer, 1, snd_pcm_frames_to_bytes(capture, frames), memstream);
            }
        }
    }

    free(buffer);
    record_close(capture);
    SnowboyDetectDestructor(detector);
    free(conv_id);
    cJSON_Delete(config);

    return NULL;
}
